package edu.wit.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.wit.acl.entity.User;
import edu.wit.acl.entity.vo.UserCorpProjectVo;
import edu.wit.acl.mapper.UserMapper;
import edu.wit.acl.service.UserService;
import edu.wit.common.api.domain.SysUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-01-12
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User selectByUsername(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public User selectById(String userId) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("id", userId));
    }

    @Override
    public String selectCompanyIdByUsername(String username) {
        return userMapper.selectCompanyIdByUsername(username);
    }
    @Override
    public void updateUserStatus(String userId, Boolean isDeleted) {
        userMapper.updateUserStatus(userId,isDeleted);
    }

    @Override
    public Integer selectTenantNums() {
        Integer tenantNums;
        tenantNums = userMapper.selectCount(new QueryWrapper<User>().eq("category",2).eq("pid",0));
        return tenantNums;
    }

    @Override
    public List<UserCorpProjectVo> selectUserCompanyByCompanyId(String companyId, String projectId) {
        return userMapper.selectUsersByCompanyId(companyId,projectId);
    }

    @Override
//    @Cacheable(value = "acl", key = "'redis_user_'+#username")
    public SysUser selectUserByUserName(String username) {
        SysUser sysUser = new SysUser();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        BeanUtils.copyProperties(user,sysUser);

        if (user.getIsDeleted()) {
            sysUser.setIsDeleted(1);
        } else {
            sysUser.setIsDeleted(0);
        }
        return sysUser;
    }

    @Override
    public boolean usernameIsExist(String username) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (null != user) {
            return true;
        }
        return false;
    }


    @Override
    public int selectManagerCount(String adminPid) {
        return userMapper.selectCount(new QueryWrapper<User>().eq("pid",adminPid))+1;
    }

    @Override
    public void updateLastLoginIp(String loginIp,Long userId) {
        userMapper.updateUserLoginIp(loginIp,userId);
    }
}
